﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    [RoleHelper(Roles = RoleSystem.Article)]
    public class ArticleCategoryController : Controller
    {

        /// <summary>
        /// Created by Vietlv
        /// Created date 05/07/2011
        /// Description: Manage ArticleCategory - Class ArticleCategory controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /ArticleCategory/Index
        public ActionResult Index(int? page)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("articleCategory.order", "order", "id").ToString();
                    string orderDir = UserState.getUserStateFromRequest("articleCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("articleCategory.Keyword", "Keyword", "").ToString();
                    keyword = keyword.Trim();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("articleCategory.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("articleCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);


                    var categories = eDataContext.ArticleCategories
                        .Where(c => CurrentPubStatus.HasValue ? c.ActiveYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    //var categories = eDataContext.ArticleCategories.OrderBy(string.Format("{0} {1}", order, orderDir)).ToList();

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new ArticleCategoryIndexViewModel
                    {
                        ArticleCategories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /ArticleCategory/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    var cat = eDataContext.ArticleCategories.Where(c => c.ID == id).SingleOrDefault();
                    var listChidrentArticle = eDataContext.ArticleCategories.Where(e => e.ParentID == id).ToList();
                    return View(new ArticleCategoryIndexViewModel
                    {
                        CurrentArticleCategory = cat,
                        ChidrentArticleCategories = listChidrentArticle
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /ArticleCategory/Create
        public ActionResult Create()
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    var listParent = eDataContext.ArticleCategories.Where(c => c.ParentID == null).ToList();
                    var languagecode = Utils.StringToDictionary(Settings.Default.LanguageCode.ToString(), ",");
                    return View(new ArticleCategoryEditViewModel
                    {
                        ParrentArticleCatrgories = listParent,
                        LanguageCode = languagecode
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /ArticleCategory/Create
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ArticleCategoryEditViewModel c)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    // TODO: Add insert logic here
                    c.ArticleCategory.Priority = Convert.ToInt32(Request["Priority"]);
                    UpdateModel(c);
                    var pid = Request["ddlParent"] != "" ? Utils.ParseInt(Request["ddlParent"]) : 0;
                    if (pid > 0)
                        c.ArticleCategory.ParentID = pid;
                    c.ArticleCategory.AddBy = UserManager.GetUserId();
                    c.ArticleCategory.AddDate = DateTime.Now;

                    eDataContext.ArticleCategories.InsertOnSubmit(c.ArticleCategory);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /ArticleCategory/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    var articlecategory = eDataContext.ArticleCategories.Where(c => c.ID == id).SingleOrDefault();
                    var listParent = eDataContext.ArticleCategories.Where(c => c.ParentID == null && c.ID != id).ToList();
                    var languagecode = Utils.StringToDictionary(Settings.Default.LanguageCode.ToString(), ",");
                    return View(new ArticleCategoryEditViewModel
                    {
                        ParrentArticleCatrgories = listParent,
                        ArticleCategory = articlecategory,
                        LanguageCode = languagecode
                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /ArticleCategory/Edit/5
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, ArticleCategoryEditViewModel c)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    // TODO: Add update logic here
                    c.ArticleCategory = eDataContext.ArticleCategories.Where(cat => cat.ID == id).SingleOrDefault();
                    var pid = Request["ddlParent"] != "" ? Utils.ParseInt(Request["ddlParent"]) : 0;
                    if (pid > 0) c.ArticleCategory.ParentID = pid;
                    c.ArticleCategory.Priority = Utils.ParseInt(Request["Priority"].ToString());
                    UpdateModel(c);
                    c.ArticleCategory.ModifyBy = UserManager.GetUserId();
                    c.ArticleCategory.ModifyDate = DateTime.Now;
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /ArticleCategory/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {
                    var item = eDataContext.ArticleCategories.Single(e => e.ID == id);
                    return View(item);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /ArticleCategory/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Article))
                {

                    var item = eDataContext.ArticleCategories.Single(e => e.ID == id);
                    if (item != null)
                    {
                        eDataContext.ArticleCategories.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
    }
}
